using UnityEngine;
using System.Collections;

public class SnakeHead : MonoBehaviour 
{
	public Rigidbody snakeTail;
	public float speed = 20;
	
	private bool wheel_mode = false;
	private bool wheel_wait = false;
	
	private Rigidbody thisRigidbody;
	private Transform thisTransform;
	
	public void Start ()
	{
		thisTransform = transform;
		thisRigidbody = rigidbody;
	}
	
	public void FixedUpdate ()
	{	
		if (!wheel_mode)
		{
			float axis = 0;
			float hor;
			float vert;
			
			hor  = Input.GetAxis ("Horizontal");
			vert = Input.GetAxis ("Vertical");
			if (hor > 0)
			{
				if (vert > 0)
					axis = 45;
				else if (vert < 0)
					axis = -45;
				else
					axis = 0;
			}
			else if (hor < 0)
			{
				if (vert > 0)
					axis = 135;
				else if (vert < 0)
					axis = 225;
				else
					axis = 180;
			}
			else
			{
				if (vert > 0)
					axis = 90;
				else if (vert < 0)
					axis = -90;
				else
					axis = 0;
			}
			
			thisTransform.rotation = Quaternion.AngleAxis (axis, thisTransform.forward);
			thisRigidbody.velocity = new Vector3 (Input.GetAxis ("Horizontal") * speed, Input.GetAxis ("Vertical") * speed - 9.8f, 0);
		}
	}
	
	public void Update ()
	{
		if (Input.GetButtonDown ("Fire2"))
			Application.LoadLevel (1);
		if (wheel_mode)
		{
			if (Input.GetButtonDown ("Jump"))
			{
				Destroy (GetComponent <SpringJoint> ());
				SendMessageUpwards ("HeadStoppedEating");
				wheel_mode = false;
				StartCoroutine ("WheelWait");
			}
		}
	}
	
	private IEnumerator WheelWait ()
	{
		wheel_wait = true;
		yield return new WaitForSeconds (1f);
		wheel_wait = false;
	}
	
	public void OnCollisionEnter (Collision other)
	{
		if (!wheel_wait && !wheel_mode)
		{
			if (other.gameObject.layer == 10)
			{
				SpringJoint joint = gameObject.AddComponent <SpringJoint> ();
				joint.connectedBody = snakeTail;
				joint.spring = 20;
				joint.damper = 0.1f;
				joint.maxDistance = 1;
				wheel_mode = true;
				SendMessageUpwards ("HeadEatingTail");
			}
		}
	}
}